import React, { useContext, useEffect, useState } from "react";
import NoAccess from "../noAccess";
import { getEntityDescription } from "../../../services/entityService";
import { accessTypes, entityNames } from "../../../constants/enums";
import { hasAccess } from "../../../services/permissionService";
import { UserContext } from "../../../context/user/userContext";
import { SubHeader } from "../subHeader";

export const Management = ({brandCode, selectedModuleName,selectedEntityName, children}) => {
 // const { waiting, setWaiting } = useState(true);
  const { state } = useContext(UserContext);
  //const { isValid, setIsValid } = useState(false);

  //const privilegesInfo = state?.user?.privileges;
  // useEffect(() => {
  //   const privileges = state?.user?.privileges;
  //   const result = hasAccess(privileges, selectedModuleName, accessTypes.READ);
  //   setIsValid(result);
  //   setWaiting(false);
  // }, [waiting, selectedModuleName]);
  // const renderModule = () => {
  //   if (isValid === true) {
  //     return children;
  //   } else {

  //     const entityDisplayName = getEntityDescription( 
  //       privileges,
  //       selectedModuleName
  //     );
  //     return <NoAccess title={entityDisplayName}></NoAccess>;
  //   }
  // };
  // if (waiting) return <React.Fragment></React.Fragment>;
  // return <React.Fragment>{renderModule()}</React.Fragment>;
  const renderModule = () => {
    const privileges = state?.user?.privileges;
    const result = hasAccess(privileges, selectedEntityName, accessTypes.READ);
    const entityDisplayName = getEntityDescription(privileges, selectedEntityName);
    if (result === true) {
      
      return children;
    } else {
      return <NoAccess title={entityDisplayName}></NoAccess>;
    }
  };
  return (
    <React.Fragment>
      <SubHeader brandCode={brandCode} selectedModuleName={selectedModuleName} selectedEntityName={selectedEntityName} />
      {renderModule()}
    </React.Fragment>)
};

export default Management;
